﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.IO;
using UnityEngine;
using System.Text;

public class JsonUtils
{

    public static T getSkill<T>(string name)
    {
        string path = "";
#if UNITY_EDITOR
        string fullUrl = string.Format("Res/Resources/Config/Skill/{0}.json", name);
        path = Path.Combine(Application.dataPath, fullUrl);
#else
        path = string.Format("Config/Skill/{0}", name);
#endif
        return getByPath<T>(path);
    }

    public static T getGround<T>(string name)
    {
        string path = "";
#if UNITY_EDITOR
        string fullUrl = string.Format("Res/Resources/Config/Ground/{0}.json", name);
        path = Path.Combine(Application.dataPath, fullUrl);
#else
        path = string.Format("Config/Ground/{0}", name);
#endif
        return getByPath<T>(path);
    }

    public static T getByPath<T>(string path)
    {
        string str;
#if UNITY_EDITOR
        str = File.ReadAllText(path);
#else
        UnityEngine.Object obj = Resources.Load(path);
        str = obj.ToString();
#endif
        return JsonConvert.DeserializeObject<T>(str);
    }



    public static void saveJson(object obj, string path)
    {
        string txt = JsonConvert.SerializeObject(obj);
        File.WriteAllText(path, txt);
    }

    public static void saveGround(object obj, string name)
    {
        string fullUrl = string.Format("Res/Resources/Config/Ground/{0}.json", name);
        string path = Path.Combine(Application.dataPath, fullUrl);
        string dir = Path.GetDirectoryName(path);
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        string txt = JsonConvert.SerializeObject(obj);
        File.WriteAllText(path, txt);
    }
}